﻿namespace dotnet_notes.Attributes
{
    /// <summary>
    /// 枚举值验证特性
    /// </summary>
    public class EnumValidationAttribute(Type enumType) : ValidationAttribute
    {
        private readonly Type enumType = enumType;

        protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
        {
            if (!enumType.IsEnum)
            {
                throw new ArgumentException($"参数 {nameof(enumType)} 是无效的枚举类型");
            }

            if (!Enum.IsDefined(enumType, value))
            {
                var infos = enumType.GetEnumInfos();
                return new ValidationResult($"无效的枚举值, 枚举定义如下: {infos.ToJson()}");
            }

            return ValidationResult.Success;
        }
    }
}
